//
//  AddNewContactListViewController.m
//  SSNDB
//
//  Created by nako on 9/19/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "AddNewContactListViewController.h"
#import "SSNDBAppDelegate.h"


@implementation AddNewContactListViewController

/* ------------------------------------------- */

@synthesize textFieldContact_date;
@synthesize textViewNote;
@synthesize receiveSSN;
@synthesize doneButton;
@synthesize saveButton;

/* ------------------------------------------- */

- (void) performDone:(id)paramSender{
	//NSLog(@"----------------%@",__FUNCTION__);
	[self.textFieldContact_date resignFirstResponder];
	[self.textViewNote resignFirstResponder];
	[self setDefaultNavigationBarButtons];
}

/* ------------------------------------------- */

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
	
	BOOL result = YES;
	
	/* Make sure we create the Done button on the top
	 right hand side of the navigation bar when we are
	 editing the contents of our text fields */
	
	if (self.editing == NO){
		[self setEditingModeNavigationBarButtons];
	}
	
	return(result);
	
}

/* ------------------------------------------- */

- (id)initWithNibName:(NSString *)nibNameOrNil 
               bundle:(NSBundle *)nibBundleOrNil {
	
	if ((self = [super initWithNibName:nibNameOrNil
								bundle:nibBundleOrNil])) {
		
		self.title = NSLocalizedString(@"Add New Person", nil);
		
	}
	
	return self;
}

/* ------------------------------------------- */

- (void) displayAlertWithTitle:(NSString *)paramTitle
                       message:(NSString *)paramMessage{
	
	/* Simply create and display an alert view using
	 the title and the message given to us */
	UIAlertView *alertView = 
	[[[UIAlertView alloc]
	  initWithTitle:paramTitle
	  message:paramMessage
	  delegate:nil
	  cancelButtonTitle:NSLocalizedString(@"OK", nil)
	  otherButtonTitles:nil, nil] autorelease];
	
	[alertView show];
	
}

/* ------------------------------------------- */

- (void)  performaddNewContactList:(id)paramSender{
	
	SSNDBAppDelegate *appDelegate = (SSNDBAppDelegate *)
	[[UIApplication sharedApplication] delegate];
	
	if (appDelegate.readSQL == YES){
		/* Get the values from the text fields */	
		NSString *aContact_date = self.textFieldContact_date.text;
	
		NSString *aNote	= self.textViewNote.text;
	
		/* Create a new instance of contact */
		Contact	*newContact = [[Contact alloc] initWithName:receiveSSN contact_date:aContact_date note:aNote];
		
		// Add new contact
		[appDelegate.contacts addObject:newContact];
	
		NSString *sqlFileName = @"SSNDB.sqlite";
		NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
		NSString *documentsDir = [documentPaths objectAtIndex:0];
		NSString *sqlFilePath = [documentsDir stringByAppendingPathComponent:sqlFileName];
	
		if (newContact != nil){
			//sqlite3 init
			sqlite3 *database;
			sqlite3_stmt *statement;
			statement = nil;
		
			if(sqlite3_open([sqlFilePath UTF8String], &database) == SQLITE_OK) {
				NSString *insertSSNDB = [ NSString stringWithFormat: @"Insert into contact(ssn,contect_date,note) values(\"%@\", \"%@\", \"%@\")",
										receiveSSN,aContact_date,aNote];
				NSLog(@"%@",insertSSNDB);
				const char *insert_stmt = [insertSSNDB UTF8String];
				sqlite3_prepare_v2(database, insert_stmt,
								   -1, &statement, NULL);
				if (sqlite3_step(statement) == SQLITE_DONE) {
					NSLog(@"Save Done");
				}else {
					NSLog(@"Save Failed..");
				}
				sqlite3_finalize(statement);
				sqlite3_close(database);
			}
		
		} else {
			/* We could not insert a new Person managed object */
			[self 
			displayAlertWithTitle:NSLocalizedString(@"New ContactList", nil)
			 message:NSLocalizedString(@"Failed To Insert A New ContactList", nil)];
		}
		[newContact release];
	}else {
		[self 
		 displayAlertWithTitle:NSLocalizedString(@"New ContactList", nil)
		 message:NSLocalizedString(@"Failed To Insert A New ContactList XMLDB", nil)];
	}
	[self.navigationController popViewControllerAnimated:YES];
}

/* ------------------------------------------- */

- (void) setDefaultNavigationBarButtons{
	
	/* By default, we have to have a Save button on the top
	 right hand side of the navigation bar */
	
	[self.navigationItem setRightBarButtonItem:self.saveButton
									  animated:YES];
	
	[self setEditing:NO];
	
}

/* ------------------------------------------- */

- (void) setEditingModeNavigationBarButtons{
	
	/* When editing the text fields, we will replace the
	 Save button with a Done button that will resign all
	 text fields from being the first responder just
	 so that the keyboard (if shown) will be hidden */
	
	[self.navigationItem setRightBarButtonItem:self.doneButton
									  animated:YES];
	
	[self setEditing:YES];
	
}

/* ------------------------------------------- */

- (void)viewDidLoad {
	[super viewDidLoad];
	
	UIBarButtonItem *newDoneButton = 
	[[UIBarButtonItem alloc]
	 initWithBarButtonSystemItem:UIBarButtonSystemItemDone
	 target:self
	 action:@selector(performDone:)];
	self.doneButton = newDoneButton;
	[newDoneButton release];
	
	UIBarButtonItem *newSaveButton = 
	[[UIBarButtonItem alloc] 
	 initWithTitle:NSLocalizedString(@"Save", nil)
	 style:UIBarButtonItemStylePlain
	 target:self
	 action:@selector(performaddNewContactList:)];
	self.saveButton = newSaveButton;
	[newSaveButton release];
	
	[self setDefaultNavigationBarButtons];
	
}

/* ------------------------------------------- */

- (void)viewDidUnload {
	[super viewDidUnload];
	
	/* Give up some memory used by our text fields
	 in case of low memory */
	
	self.textFieldContact_date = nil;
	self.textViewNote = nil;
	self.receiveSSN = nil;
	self.doneButton = nil;
	self.saveButton = nil;
	
}

/* ------------------------------------------- */

- (BOOL)shouldAutorotateToInterfaceOrientation:
(UIInterfaceOrientation)interfaceOrientation {
	// Return YES for supported orientations
	return (YES);
}

/* ------------------------------------------- */

- (void)didReceiveMemoryWarning {
	[super didReceiveMemoryWarning];
}

/* ------------------------------------------- */

- (void)dealloc {
	[textFieldContact_date release];
	[textViewNote release];
	[receiveSSN release];
	[doneButton release];
	[saveButton release];
	[super dealloc];
}

/* ------------------------------------------- */



@end
